﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Meraz.Web.Models.Admin;
using Meraz.Core.Providers;
using Ninject;
using System.Web.Security;
using Meraz.Core.Managers;
using Meraz.Web.Models;
using Meraz.Web.Models.Home;

namespace Meraz.Web.Controllers
{
    public class AdminController : Controller
    {
        public AdminController()
        {
            CustomMembershipProvider = (ICustomMembershipProvider)Membership.Providers["custom"];
            CustomRoleProvider = (ICustomRoleProvider)Roles.Providers["custom"];
        }

        [Inject]
        public UrlManager UrlManager { get; set; }

        public ICustomMembershipProvider CustomMembershipProvider { get; set; }

        public ICustomRoleProvider CustomRoleProvider { get; set; }
        [Authorize]
        public ActionResult Index()
        {
            ViewData["Menu"] = Menu.Admin;
            return View();
        }

        [Authorize]
        public ActionResult Welcome()
        {
            ViewData["Menu"] = Menu.Admin;
            return View();
        }

        [HttpPost]
        public ActionResult Authenticate(string Username, string Password, string Persist)
        {
            if (HttpContext.User.Identity.IsAuthenticated)
                return Redirect("/Home/Index");

            ViewData["Menu"] = Menu.Admin;
            bool valid = false;
            try
            {
                valid = CustomMembershipProvider.ValidateUser(Username, Password);

                if (valid)
                {
                    FormsAuthentication.SetAuthCookie(Username, !string.IsNullOrEmpty(Persist));
                    if (this.Request.QueryString != null)
                    {
                        string redirect = Request.QueryString["ReturnUrl"];
                        if (!string.IsNullOrWhiteSpace(redirect))
                            Redirect(redirect);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ViewData["Message"] = "Your credentials were incorrect. Try again.";
            }
            catch (Exception problem)
            {
                ViewData["Message"] = problem.Message;
            }
            Password = "";
            return View();
        }
        
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(string OldPassword, string NewPassword, string ConfirmPassword)
        {
            ViewData["Menu"] = Menu.Admin;
            string username = HttpContext.User.Identity.Name;
            string Message = null;
            MembershipUser user = CustomMembershipProvider.GetUser(username, true);
            if (string.IsNullOrWhiteSpace(OldPassword))
            {
                Message = "Old password is required.";
            }
            else if (string.IsNullOrWhiteSpace(NewPassword))
            {

                Message = "New password is invalid.";
            }
            else if (NewPassword != ConfirmPassword)
            {
                Message = "Re-enter new password.";
            }
            else
            {
                bool result = CustomMembershipProvider.ChangePassword(username, OldPassword, NewPassword);
                if (result)
                {
                    Message = "Password is changed!";
                }
                else
                    Message = "An error occured. Please try this again later.";
            }
            ViewData["Message"] = Message;
            return Redirect("/");
        }
       
        public ActionResult Register()
        {
            ViewData["Menu"] = Menu.Admin;
            ViewData["PasswordLength"] = CustomMembershipProvider.MinRequiredPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel registerModel)
        {
            ViewData["Menu"] = Menu.Admin;
            MembershipCreateStatus createStatus;
            try
            {
                MembershipUser user = CustomMembershipProvider.CreateUser(registerModel.Username, registerModel.Password, registerModel.Email, registerModel.Question, registerModel.Answer, true, Guid.NewGuid(), out createStatus);
            }
            catch
            {
                createStatus = MembershipCreateStatus.UserRejected;
            }
            string message = null;
            switch (createStatus)
            {
                case MembershipCreateStatus.Success:
                    string[] usernames = new string[]{registerModel.Username};
                    string[] rolenames = new string[]{"User"};
                    CustomRoleProvider.AddUsersToRoles(usernames, rolenames);
                    FormsAuthentication.SetAuthCookie(registerModel.Username, false);
                    return Redirect("/");
                case MembershipCreateStatus.DuplicateEmail:
                    message = "Another user has claimed this email address. Please enter a different one.";
                    break;
                default:
                    message = "There was a problem with your registration form. Please check your values and try again.";
                    break;
            }
            this.ViewData["Message"] = message;
            return View("Register", registerModel);
        }

        [RolesAuthorize(Roles = UserRoles.Admin)]
        public ActionResult Rights()
        {
            ViewData["Menu"] = Menu.Admin;
            return View();
        }

        [Authorize]
        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            return Redirect("/");
        }

        [Authorize]
        [RolesAuthorize(Roles = UserRoles.Editor)]
        public ActionResult UrlRedirects()
        {
            ViewData["Menu"] = Menu.Admin;
            return View();
        }

        [HttpPost]
        [RolesAuthorize(Roles = UserRoles.Editor)]
        public ActionResult UrlRedirects(UrlRedirectsModel model)
        {
            ViewData["Menu"] = Menu.Admin;
            if (model.Button.Equals("Add", StringComparison.InvariantCultureIgnoreCase))
            {

                UrlManager.AddRedirect(model.Redirect, model.Destination);
            }
            else
            {
                //upload file and parse
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;
                    try
                    {
                        UrlManager.LoadRedirects(hpf.InputStream);
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            if (hpf.InputStream != null)
                                hpf.InputStream.Close();
                        }
                        catch
                        {
                        }
                    }
                }
            }

            model.Destination = string.Empty;
            model.Redirect = string.Empty;
            return View(model);
        }
    }
}
